package com.py.credit.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.py.credit.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Account;
import com.py.credit.entity.DictDetailEntity;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.MulQureryEnum;
import com.py.credit.entity.enums.ReportEnum;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.NumberUtils;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/mul/front")
public class OrgMulQueryController {

	@Autowired
	private MulQueryService mulQueryService;
	@Autowired
	private EvalInfoService evalInfoService;
	@Autowired
	private ModelBaseService modelBaseService;
	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;
	@Autowired
	private GatewayUserService userService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private SysDictService sysDictService;

	private static final String FRONT_TABLE_ID = "report";

	private static final String REPORT_COUNT_ID = "accountReport";

	@Value("${absolutepathReport}")
	private String absolutepathReport;

	// 报告类型常量
	private static final String BGLX = "BGLX";

	/**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(MulQureryEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	@IgnoreAuthority
	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<LinkedHashMap<String, Object>>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = false) String condition, String sqr_str,
			String reportType, String shzt, Page page, HttpServletRequest request) {
		RestServiceResult<List<LinkedHashMap<String, Object>>> r = new RestServiceResult<>();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {
			String[] additionalColumns = { "id", "modelId", "sqr", "scoreType", "zone", "industry", "checkProcess" };
			String[] configColumns = (String[]) MapCache.get(account.getId() + "_" + FRONT_TABLE_ID);
			List<String> showColumns = (configColumns == null || configColumns.length == 0)
					? MulQureryEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
			try {
				List<LinkedHashMap<String, Object>> tableList = mulQueryService.getByConditionForPage(showColumns,
						additionalColumns, condition, page, account.getOrgId(), sqr_str, reportType, shzt);
				r = new RestServiceResult<>(page.getTotalCount(), tableList);
			} catch (Exception e) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("系统异常！");
			}

		}
		return r;
	}

	@RequestMapping(value = "/export")
	public RestServiceResult<List<LinkedHashMap<String, Object>>> exportData(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, String orgId,
			String sqr_str, String reportType, String shzt, Page page, HttpServletResponse response,
			HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<LinkedHashMap<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		page.setLimit(1000);
		String[] configColumns = (String[]) MapCache.get(account.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? MulQureryEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		List<LinkedHashMap<String, Object>> tableList = mulQueryService.getByConditionForPage(showColumns, null,
				condition, page, account.getOrgId(), sqr_str, reportType, shzt);
		try {
			ExcelUtil.downloadLinkExcel(response, tableList, "综合查询", "综合查询", showColumns,
					MulQureryEnum.getOptionalColumns());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("综合查询导出异常，请稍后再试！");
			ExceptionLogger.error("综合查询导出异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(MulQureryEnum.getAdvancedConditionColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> r = new RestServiceResult<String>();
		try {
			HttpSession session = request.getSession();

			Account account = (Account) session.getAttribute("ACCOUNT");
			MapCache.set(account.getId() + "_" + FRONT_TABLE_ID, columns);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	@RequestMapping(value = "/viewCheck.json")
	public RestServiceResult<List<Map>> viewCheck(String modelId, String sqr, String evalId,
			HttpServletResponse response, HttpServletRequest request) {
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		List<Map> list = evalInfoService.viewCheck(modelId, sqr, evalId);
		result.setData(list);
		return result;

	}

	@RequestMapping(value = "/getTotalScore.do")
	public RestServiceResult<Map> getTotalScore(String sqr, String modelId, String evalId, HttpServletResponse response,
			HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Map> result = new RestServiceResult<>();
		try {
			Map<String, Object> scoreMap = evalInfoService.getTotalScore(evalId);
			double scoreAdd = evalInfoService.getExtraScore(evalId, "add");
			double scoreSubtraction = evalInfoService.getExtraScore(evalId, "subtraction");
			double score = (Double) (scoreMap.get("score")) + scoreAdd + scoreSubtraction;
			double score1 = (Double) (scoreMap.get("score1"));
			double score2 = (Double) (scoreMap.get("score2"));
			double score3 = (Double) (scoreMap.get("score3"));
			double score4 = (Double) (scoreMap.get("score4"));
			double score5 = (Double) (scoreMap.get("score5"));
			double score6 = (Double) (scoreMap.get("score6"));
			Map m = modelBaseService.selectOne(modelId);
			double rate = (double) m.get("rate");
			String scoreType = (String) m.get("scoreType");
			if (StringUtils.isNotBlank(scoreType) && "1".equals(scoreType) && rate != 0) {
				score = NumberUtils.getDouble(2, rate * score / 100);
				scoreAdd = NumberUtils.getDouble(2, rate * scoreAdd / 100);
				scoreSubtraction = NumberUtils.getDouble(2, rate * scoreSubtraction / 100);
			}
			scoreMap.replace("score", String.valueOf(score));
			scoreMap.replace("score1", NumberUtils.getDouble(2, rate * score1 / 100));
			scoreMap.replace("score2", NumberUtils.getDouble(2, rate * score2 / 100));
			scoreMap.replace("score3", NumberUtils.getDouble(2, rate * score3 / 100));
			scoreMap.replace("score4", NumberUtils.getDouble(2, rate * score4 / 100));
			scoreMap.replace("score5", NumberUtils.getDouble(2, rate * score5 / 100));
			scoreMap.replace("score6", NumberUtils.getDouble(2, rate * score6 / 100));
			scoreMap.put("scoreSubtraction", String.valueOf(scoreSubtraction));
			scoreMap.put("scoreAdd", String.valueOf(scoreAdd));
			List<Map> l = evalInfoService.getScoreRank(score, modelId);
			if (l != null && l.size() > 0) {
				Map rank = l.get(0);
				String scoreRank = String.valueOf(rank.get("name") == null ? "" : rank.get("name"));
				String evalInfo = String.valueOf(rank.get("evalInfo") == null ? "" : rank.get("evalInfo"));
				scoreMap.put("scoreRank", scoreRank);
				scoreMap.put("evalInfo", evalInfo);
			}

			result.setData(scoreMap);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取评价评分异常，请稍后再试！");
			ExceptionLogger.error("获取评价评分异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/getReportCountColums.json")
	public RestServiceResult<List<OptionalColumn>> getReportCountColums() {
		return new RestServiceResult<List<OptionalColumn>>(ReportEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getDefaultReportCountColums.json")
	public RestServiceResult<List<String>> getDefaultReportCountColums() {
		return new RestServiceResult<List<String>>(ReportEnum.getDefaultShowColumnEN());
	}

	@RequestMapping(value = "/getAdvancedReportCountColums.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedReportCountColums() {
		return new RestServiceResult<List<OptionalColumn>>(ReportEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addReportShowColunms.json")
	public RestServiceResult<String> addReportShowColunms(
			@RequestParam(value = "columns", required = true) String[] columns, HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {
			String column = StringUtils.join(columns, ",");
			MapCache.set(account.getId() + "_" + REPORT_COUNT_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("添加展示字段失败！");
			return result;
		}
		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/exportAccount")
	public RestServiceResult<List<Map<String, Object>>> exportAccount(
			@RequestParam(value = "reportType", defaultValue = "", required = true) String reportType,
			@RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
			@RequestParam(value = "recieveStatus", defaultValue = "", required = true) String recieveStatus,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<OptionalColumn> optionalColumns = ReportEnum.getOptionalColumns();
		List<Map<String, Object>> data;
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {
			try {
				data = mulQueryService.selectAllReportGet(reportType, mainType, recieveStatus, account.getOrgId(),
						showColumns, null, condition, page);
				if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
					return result;
				}
				ExcelUtil.downloadExcel(response, data, "报告领取列表", "报告领取列表", showColumns, optionalColumns);
				return result;
			} catch (Exception e) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("报告领取导出异常，请稍后再试！");
				ExceptionLogger.error("报告领取导出异常！", e.getMessage(), e);
				return result;
			}
		} else {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("未登录，请登录！");
			return result;
		}

	}

	@RequestMapping(value = "/selectAllReportGet.json")
	public RestServiceResult<List<Map<String, Object>>> selectAllReportGet(
			@RequestParam(value = "reportType", defaultValue = "", required = true) String reportType,
			@RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
			@RequestParam(value = "recieveStatus", defaultValue = "", required = true) String recieveStatus,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {

			String[] configColumns = (String[]) MapCache.get(account.getId() + "_" + REPORT_COUNT_ID);
			List<String> showColumns = (configColumns == null || configColumns.length == 0)
					? ReportEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
			List<Map<String, Object>> data;
			try {
				rep = mulQueryService.selectAllReportGet(reportType, mainType, recieveStatus, account.getOrgId(),
						showColumns, new String[] { "id", "orgId" }, condition, page);
				r.setCount(page.getTotalCount());
			} catch (Exception e) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg(e.getMessage());
				ExceptionLogger.error("reportGet#selectAllReportGet", "报告信息查询失败");
			}
			r.setData(rep);
			return r;
		} else {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("未登录，请登录！");
			return r;
		}
	}

	@RequestMapping(value = "/updateReportshzt.json")
	public RestServiceResult updateReportshzt(@RequestParam(value = "bgbh", required = true) String bgbh,
			@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "lqr", required = true) String lqr,
			@RequestParam(value = "lqtype", required = true) String lqtype,
			@RequestParam(value = "lqbz", required = true) String lqbz,
			@RequestParam(value = "file", required = true) String file, HttpServletRequest request) {
		RestServiceResult r = new RestServiceResult();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {
			try {
				mulQueryService.updateReportshzt(bgbh, id, lqr, lqtype, lqbz, file, account.getOrgId());
				r.setMsg("报告资料提交成功");
			} catch (Exception e) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg(e.getMessage());
				ExceptionLogger.error("reportGet#updateReportshzt", "报告资料提交失败");
			}
			return r;
		} else {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("未登录，请登录！");
			return r;
		}
	}

	@RequestMapping(value = "/updateReportWj.json")
	public RestServiceResult<Map<String, String>> updateReportWj(MultipartFile file) {
		RestServiceResult<Map<String, String>> r = new RestServiceResult<Map<String, String>>();
		Map<String, String> map = new HashMap<String, String>();
		if (!file.getOriginalFilename().toLowerCase().endsWith(".zip")
				&& !file.getOriginalFilename().toLowerCase().endsWith(".rar")
				&& !file.getOriginalFilename().toLowerCase().endsWith(".7z")) {
			r.setMsg("压缩包格式错误");
		}
		if (file.getSize() > 10 * 1024) {
			r.setMsg("文件大小超过10M");
		}
		String dirPath = absolutepathReport + File.separator + "领取凭证_" + File.separator + UuidUtil.getUUid();
		try {
			map.put("fileUrl", dirPath + File.separator + "领取凭证_" + file.getOriginalFilename());
			r.setData(map);
			userService.fileUpload(file, dirPath, "领取凭证_");
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg(e.getMessage());
			ExceptionLogger.error("reportGet#updateReportWj", "压缩包上传失败");
		}
		return r;
	}

	@RequestMapping(value = "/selectReportHistoryForPage.json")
	public RestServiceResult<List<Map<String, Object>>> selectReportHistoryForPage(
			@RequestParam(value = "bgbh", required = true) String bgbh,
			@RequestParam(value = "lqr", defaultValue = "", required = true) String lqr, HttpServletRequest request,
			Page page) {
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {
			try {
				rep = mulQueryService.selectReportHistoryForPage(bgbh, lqr, account.getOrgId(), page);
				r.setCount(page.getTotalCount());
			} catch (Exception e) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg(e.getMessage());
				ExceptionLogger.error("reportGet#selectReportHistoryForPage", "报告历史信息查询失败");
			}
			r.setData(rep);
			return r;
		} else {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("未登录，请登录！");
			return r;
		}
	}

	@RequestMapping(value = "/isReportFile.json")
	public RestServiceResult isReportFile(@RequestParam(value = "fileUrl", required = true) String fileUrl,
			HttpServletRequest request) {
		RestServiceResult r = new RestServiceResult();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {
			File file = new File(fileUrl);
			if (!file.exists()) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("暂无报告资料");
				ExceptionLogger.error("reportGet#isReportFile", "暂无报告资料");
			}
			return r;
		} else {

			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("未登录，请登录！");
			return r;
		}

	}

	@RequestMapping(value = "/downReportFile.json")
	public void downReportFile(@RequestParam(value = "fileUrl", required = true) String fileUrl,
			HttpServletResponse response, HttpServletRequest request) {
		RestServiceResult r = new RestServiceResult();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (null != account) {
			if (!FileUtil.downloadFile(fileUrl, response)) {
				r.setMsg("下载失败，请稍后再试");
				ExceptionLogger.error("reportGet#downReportFile", "报告资料领取失败");
			}
		}

	}

	@RequestMapping(value = "/getEvaDictory.json")
	public RestServiceResult getEvaDictory() {
		RestServiceResult r = new RestServiceResult<List<DictDetailEntity>>();
		Map<String, Object> map = new HashMap<>();
		try {
			List<DictDetailEntity> list = sysDictService.getDictDetails(BGLX, StringUtils.EMPTY);
			map.put(BGLX, list);
			r.setData(map);
			return r;
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("字典值查询失败！");
			return r;
		}
	}

	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	@ApiOperation(value = "修改密码", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "oldPassword", value = "旧密码", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "newPassword", value = "新密码", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "newPassword2", value = "新密码2", required = true) })
	public RestServiceResult<Object> updatePassword(String oldPassword, String newPassword, String newPassword2,
			HttpServletRequest request) {
		RestServiceResult<Object> r = new RestServiceResult<Object>();
		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		Integer accountId = account.getId();

		if (StringUtils.isBlank(oldPassword)) {

		} else {
			Account user = orgService.select(String.valueOf(accountId));
			if (null == user) {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("该用户不存在");
			} else {
				if (!oldPassword.equals(user.getPassword())) {
					r.setCode(RestServiceResult.CODE_UNKNOW);
					r.setMsg("原密码填写错误！");
				} else {
					if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(newPassword2)
							&& newPassword.equals(newPassword2)) {
						try {
							Account entity = new Account();
							entity.setId(accountId);
							entity.setPassword(newPassword);
							orgService.updatePassword(String.valueOf(accountId), newPassword);
							;
							r.setCode(RestServiceResult.CODE_SUCCESS);
							r.setMsg("密码修改成功！");
						} catch (Exception e) {
							r.setCode(RestServiceResult.CODE_UNKNOW);
							r.setMsg("更新失败！");
							ExceptionLogger.error(e);
						}
					} else {
						r.setCode(RestServiceResult.CODE_UNKNOW);
						r.setMsg("新密码有误！");
					}
				}
			}
		}
		return r;
	}
}
